/*
  学习目标：连接小智同学, 实现聊天功能
  步骤：
    
*/
import Icon from "@/components/Icon";
import Input from "@/components/Input";
import NavBar from "@/components/NavBar";
import { Toast } from "antd-mobile";
import classNames from "classnames";
import { useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import { io, Socket } from "socket.io-client";
import { getAuth } from "@/utils/storage";

interface IChatInfo {
  msg: string;
  type: "user" | "robot";
  timestamp: number;
}

export default function Chat() {
  const [list, setList] = useState<IChatInfo[]>([]);

  // 3. 创建ref, 保存client
  const clientRef = useRef<Socket | null>(null);
  useEffect(() => {
    // 1. 创建客户端实例
    clientRef.current = io("http://geek.itheima.net", {
      query: {
        token: getAuth().token,
      },
      transports: ["websocket"],
    });
    // 2. 监听连接成功, 显示欢迎语
    clientRef.current.on("connect", () => {
      setList([
        { msg: "您好, 有什么可以会帮您", type: "robot", timestamp: Date.now() },
      ]);
    });

    // 5. 接受消息
    clientRef.current.on("message", (data) => {
      setList((preList) => [...preList, { ...data, type: "robot" }]);
    });

    return () => {
      // 6. 卸载时,关闭websocket
      clientRef.current?.close();
    };
  }, []);

  const [msg, setMsg] = useState("");

  const handleSendMsg = () => {
    if (!msg.trim()) return Toast.show("不能发送空消息");
    setList([...list, { msg, type: "user", timestamp: Date.now() }]);
    setMsg("");
    // 4. 发送消息
    clientRef.current?.emit("message", { msg, timestamp: Date.now() });
  };
  useEffect(() => {
    window.scrollTo({ top: document.body.scrollHeight, behavior: "smooth" });
  }, [list]);
  return (
    <div className={styles.root}>
      <NavBar fixed>小智同学</NavBar>

      <div className="chat-list">
        {list.map((item) => {
          return (
            <div
              key={item.timestamp}
              className={classNames("chat-item", {
                user: item.type === "user",
              })}
            >
              {item.type === "robot" ? (
                <Icon type="iconbtn_xiaozhitongxue" />
              ) : (
                <img
                  alt=""
                  src={"http://toutiao.itheima.net/images/user_head.jpg"}
                />
              )}

              <div className="message">{item.msg}</div>
            </div>
          );
        })}
      </div>

      <div className="footer">
        <div className="input-footer">
          <Input
            value={msg}
            onChange={(e) => setMsg(e.target.value)}
            className="no-border"
            placeholder="请描述您的问题"
          />
          <Icon type="iconbianji" />
          <span onClick={handleSendMsg} className="send">
            发送
          </span>
        </div>
      </div>
    </div>
  );
}
